package com.zengde.zxfy.controller;

import com.zengde.zxfy.common.Result;
import com.zengde.zxfy.dto.LoginDTO;
import com.zengde.zxfy.dto.LoginResponseDTO;
import com.zengde.zxfy.entity.Emp;
import com.zengde.zxfy.service.EmpService;
import com.zengde.zxfy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    private EmpService empService;
    
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@RequestBody LoginDTO loginDTO) {
        // 根据用户名查询员工
        Emp emp = empService.getByUsername(loginDTO.getUsername());
        
        // 判断员工是否存在
        if (emp == null) {
            return Result.error("用户名或密码错误");
        }
        
        // 密码比对
        if (!emp.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        
        // 生成JWT令牌
        String token = jwtUtils.generateToken(emp.getId(), emp.getUsername());
        
        // 构建响应数据
        LoginResponseDTO responseDTO = LoginResponseDTO.builder()
                .id(emp.getId())
                .username(emp.getUsername())
                .name(emp.getName())
                .token(token)
                .build();
        
        return Result.success(responseDTO);
    }
} 